import {HttpContextContract} from "@ioc:Adonis/Core/HttpContext";
import Spus from "App/Models/Spus";
import Skus from "App/Models/Skus";
import Redis from "@ioc:Adonis/Addons/Redis";
export default class SpusController {
  //添加Spu信息
  public async addSpu(ctx: HttpContextContract) {
      //获取用户
      this.writeLog(ctx,"addSpu","添加商品信息");
      const params:any=ctx.request.body();
      let sukList=new Array<Skus>();
      let spu = await Spus.updateOrCreate({id:params.id?params.id:""},{name:params.name,description:params.description});
      let skus=Skus.query().where('spu_id','=',params.id);
      await skus.delete();
      for(let i=0;i<params.skuList.length;i++){
          let curItem:any=params.skuList[i];
          let sku=new Skus();
          sku.spuId=spu.id;
          sku.images=curItem.images;
          sku.name=curItem.name;
          sku.price=curItem.price;
          sku.stock=curItem.stock;
          sku.params=curItem.params;
          sukList.push(sku);
      }
      //建立Spu和Sku的关系
      sukList.forEach(async skuItem=> {
            let skuDbData=await Skus.create(skuItem);
            skuDbData.related('params').createMany(skuItem.params);
      });
  }
  //查询Spu信息,需要分页加上模糊查询淡出提取
  public async getSpuList(ctx: HttpContextContract){
      this.writeLog(ctx,"getSpuList","获取后台Spu信息");
      const loginUser=ctx.session.get("loginUser");
      if(!loginUser){
          return {status:1};
      }
      const params:any=ctx.request.body();
      let spus=new Array();
      if(params.name){
          spus = await Spus.query().
          andWhereRaw("name like ?",[`%${params.name}%`]).
          forPage(params.pager.currentPage,params.pager.pageSize);
          let countResult:any=await Spus.query().andWhereRaw("name like ?",[`%${params.name}%`]).count("name");
          let count=countResult[0]['$extras']['count(`name`)'];
          return {data:spus.map((spu) => spu.toJSON()),count:count};
      }
      spus=  await Spus.query().forPage(params.pager.currentPage,params.pager.pageSize);
      let countResult=await Spus.query().count('name');
      let count=countResult[0]['$extras']['count(`name`)'];
      return {data:spus.map((spu) => spu.toJSON()),count:count};
  }
  //根据条件查询商品的单个Spu信息，Sku信息以及规格参数信息
  public async getSpuListByCondition(ctx: HttpContextContract){
      this.writeLog(ctx,"getSpuListByCondition","访问商品详情页");
      const params:any=ctx.request.body();
      let spu=Spus.query().where("id","=",params.id).preload('skus',(skuQuery)=>{
           skuQuery.preload('params');
      });
      return spu;
  }
  //根据名称查询
  public async getSpuListByName(ctx: HttpContextContract){
      this.writeLog(ctx,"getSpuListByName","访问商品首页");
      const params:any=ctx.request.body()
      if(params.name){
         return Spus.query().where("name","like",`%${params.name}%`).preload('skus');
      }
      return Spus.query().preload('skus');
  }
  //删除商品
  public async deleteProduct(ctx: HttpContextContract){
      this.writeLog(ctx,"deleteProduct","删除商品");
      const params:any=ctx.request.body();
      let spu=Spus.query().where("id","in",params.ids);
      await spu.delete();
  }
  //异步记录用户访问日志
  public writeLog(ctx,methodName,description){
     const loginUser=ctx.session.get("loginUser");
     if(loginUser){
        let logInfo={username:loginUser.username,methodName:methodName,description:description};
        //Redis.publish('log:userActions', JSON.stringify(logInfo));
     }
  }
}
